package com.gupao.edu.homework.chatroom;

import com.gupao.edu.utils.CloseUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @description：
 * @author：huabin.lin@xhmh.com
 * @version：2018年11月04日 20:19
 */
public class ClientSend implements Runnable {
    /***
     * 控制台输入流
     */
    private BufferedReader console;
    /***
     * 输出流
     */
    private PrintWriter out;
    /***
     * 线程运行标识
     */
    private boolean isRunning = true;
    /***
     * 客户端名称
     */
    private String name;

    public ClientSend() {
        super();
        console = new BufferedReader(new InputStreamReader(System.in));
    }

    public ClientSend(Socket client, String name) {
        this();
        try {
            this.out = new PrintWriter(client.getOutputStream());
            this.name = name;
            this.send(this.name);
        } catch (IOException e) {
            e.printStackTrace();
            this.isRunning = false;
            CloseUtil.clearResources(this.out, this.console);
        }
    }

    /***
     * 从控制台获取数据
     * @return
     */
    private String getDataFromConsole() {
        try {
            return this.console.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     * 向服务端发送数据
     * @param data
     */
    private void send(String data) {
        if (null != data && !"".equals(data)) {
            this.out.println(data);
            this.out.flush();
        }
    }

    @Override
    public void run() {
        while (this.isRunning) {
            this.send(this.getDataFromConsole());
        }
    }
}
